package com.ruoyi.system.service.impl;

import com.ruoyi.system.mapper.RecordsMapper;
import com.ruoyi.system.service.IRecordsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class RecordsServiceImpl implements IRecordsService {

    @Autowired
    private RecordsMapper recordsMapper;

    @Override
    public List<Map<String, Object>> selectDeptAttendanceStats(String deptName) {
        List<Map<String, Object>> stats = recordsMapper.selectDeptAttendanceStats(deptName);

        // 如果没有搜索条件，返回所有部门数据
        if (StringUtils.isEmpty(deptName)) {
            return stats;
        }

        // 如果有搜索条件，需要返回匹配部门及其所有子部门
        Set<Long> matchedDeptIds = new HashSet<>();
        Set<Long> allDeptIds = new HashSet<>();

        // 收集匹配的部门ID
        stats.forEach(item -> matchedDeptIds.add(Long.parseLong(item.get("deptId").toString())));

        // 获取所有部门数据
        List<Map<String, Object>> allDepts = recordsMapper.selectDeptAttendanceStats(null);

        // 为每个匹配的部门查找所有子部门
        matchedDeptIds.forEach(deptId -> {
            allDepts.stream()
                    .filter(dept -> {
                        String ancestors = dept.get("ancestors").toString();
                        return ancestors.contains("," + deptId + ",") ||
                                ancestors.startsWith(deptId + ",") ||
                                ancestors.endsWith("," + deptId);
                    })
                    .forEach(dept -> allDeptIds.add(Long.parseLong(dept.get("deptId").toString())));
        });

        // 合并匹配的部门ID和子部门ID
        allDeptIds.addAll(matchedDeptIds);

        // 返回匹配部门及其子部门的数据
        return allDepts.stream()
                .filter(dept -> allDeptIds.contains(Long.parseLong(dept.get("deptId").toString())))
                .collect(Collectors.toList());
    }

    // ... 其他原有方法
}